package cn.gyyx.tools.sign.service;

import cn.gyyx.tools.sign.beans.CallResult;
import cn.gyyx.tools.sign.beans.ExtResult;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.GetRequest;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * 掉用第三方地址服务
 */
public class CallService extends ServiceBase {

    public ExtResult<CallResult> call(String urlStr) {

        ExtResult<CallResult> extResult = new ExtResult<CallResult>();
        CallResult callResult =new CallResult();
        extResult.setData(callResult);

        /**
         * 1.检查参数
         * 未符合标准则返回
         */
        URI uri = null;
        try {
            uri = new URI(urlStr);
        } catch (URISyntaxException ex) {
            logger.error(ex.getMessage());
            extResult.setIsSuccess(false);
            extResult.setMessage("请求过程-检查参数-"+ex.getMessage());
            return extResult;
        }

        /**
         * 2.使用unirest请求目标
         * 请求失败返回Result
         */
        GetRequest getRequest = Unirest.get(urlStr);
        HttpResponse<String> response=null;
        try{
            response = getRequest.asString();
        } catch (UnirestException e) {
            e.printStackTrace();
            extResult.setIsSuccess(false);
            extResult.setMessage("请求过程-请求第三方-"+e.getMessage());
            return extResult;
        }

        /**
         * 3.初始化CallResult
         */
        callResult.setHttpStatusCode(response.getStatus());
        callResult.setBody(response.getBody());
        extResult.setIsSuccess(true);
        return extResult;
    }
}
